<?php

namespace plugin\owladmin\console;

use Illuminate\Console\Command;
use plugin\owladmin\app\service\AdminApiService;
use plugin\owladmin\app\service\AdminCodeGeneratorService;
use plugin\owladmin\app\support\CodeGenerator\ControllerGenerator;

class GenRouteCommand extends Command
{
    protected $signature = 'admin:gen-route {--excluded=}';

    protected $description = 'Generate admin route file.';

    public function handle(): void
    {
        $content = <<<EOF
<?php

// =====================================================================

// !!  路由文件由 owl-admin 自动生成，请不要手动修改。

// !!  Route file auto generated by owl-admin, don't modify it manually.

// =====================================================================

use plugin\owladmin\app\Admin;use Illuminate\Routing\Router;use Illuminate\Support\Facades\Route;

Route::group([
    'domain'     => Admin::config('admin.route.domain'),
    'prefix'     => Admin::config('admin.route.prefix'),
    'middleware' => Admin::config('admin.route.middleware'),
], function (Router \$router) {
_content_
});
EOF;


        $excluded = $this->option('excluded');
        if ($excluded) {
            $excluded = explode(',', $excluded);
        }

        $routes = '';

        // 代码生成器
        AdminCodeGeneratorService::make()->query()
            ->when($excluded, fn($query, $excluded) => $query->whereNotIn('id', $excluded))
            ->get()
            ->map(function ($item) use (&$routes) {
                if (!$item->menu_info['enabled']) return;

                $_route      = ltrim($item->menu_info['route'], '/');
                $_controller = '\\' . str_replace('/', '\\', $item->controller_name);

                try {
                    require_once ControllerGenerator::guessClassFileName($_controller);
                } catch (\Throwable $e) {
                }

                if (!class_exists($_controller)) {
                    return;
                }

                $routes .= <<<EOF
    // {$item->title}
    \$router->resource('{$_route}', {$_controller}::class);

EOF;
            });

        // api
        AdminApiService::make()->query()->where('enabled', 1)->get()->map(function ($item) use (&$routes) {
            $_route = ltrim($item->path, '/');

            $routes .= <<<EOF
    // {$item->title}
    \$router->{$item->method}('{$_route}', [\plugin\owladmin\controller\AdminApiController::class, 'index']);

EOF;
        });

        $content = str_replace('_content_', $routes, $content);

        file_put_contents(base_path('routes/admin.php'), $content);

        $this->info('Route file generated successfully.');
    }
}
